package com.weisha.bledemo.application;

import java.util.concurrent.TimeUnit;

import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.weisha.bledemo.retrofit.CommonOkHttp;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;


public class App extends Application {

    public static OkHttpClient okHttpClient;
    public static ClearableCookieJar cookieJar;
    private static App instance;
    public static String password;
    public static String deviceId;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initializeClient();
    }

    private void initializeClient() {
        cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(instance));
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        okHttpClient = new OkHttpClient.Builder()
                .cookieJar(cookieJar)
                .addInterceptor(interceptor)
                .readTimeout(7676, TimeUnit.MILLISECONDS)
                .connectTimeout(7676, TimeUnit.MILLISECONDS)
                .build();
        cookieJar.loadForRequest(HttpUrl.parse(CommonOkHttp.baseUrl));
    }

    public static OkHttpClient getClient() {
        return okHttpClient;
    }

    public static String getCurProcessName(Context context) {

        int pid = android.os.Process.myPid();

        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);

        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {

            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }
}
